import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@store'
import guard from './guards'
import AppRoute from '@light-app/router'
import { publicPath } from '@light-app/config'

Vue.use(VueRouter)

const distributeRoute = {
    name: 'distribute',
    path: '*',
    meta: {
        title: '自动登录'
    },
    component: () =>
        import('@views/_common/distribute')
}

const errorRoute = {
    name: 'error',
    path: '/error',
    meta: {
        title: '出错了'
    },
    component: () =>
        import('@views/_common/error')
}

export const getAppRoute = (ar) => {
    const func = (path, routes) => {
        routes.forEach(r => {
            // console.log(!r.children?r.meta.title:"nonono")
            const routePath = (path + '/' + r.path).replace(/(\/){2,}/g, '/')

            if (r.children && r.children.length > 0) {
                func(routePath, r.children)
            } else {
                r.path = routePath
            }
        })
    }

    func(ar.path, ar.children)

    return { ...ar }
}

// export const initAppRoute = getAppRoute(appRoute);
let initAppRoute

export const getSidebarRoutes = () => initAppRoute.children

export const getMatcherRoutes = () => {
    //新增根据权限显示路由
    const userInfo = JSON.parse(localStorage.getItem("user"))
    var appRoute1 = userInfo && userInfo.is_admin == 1 ? AppRoute.adminRouter : AppRoute.perRouter;
    initAppRoute = getAppRoute(appRoute1)
    getSidebarRoutes()

    if (!appRoute1 || !appRoute1.children) {
        throw 'AppRoute is required'
    }

    const _routes = []

    const func = (routes) => {
        routes.forEach(ar => {
            if (ar.children && ar.children.length > 0) {
                func(ar.children)
            } else {
                _routes.push(ar)
            }
        })
    }

    func(initAppRoute.children)

    return {
        ...appRoute1,
        children: _routes
    }
}

export const resetRouter = () => {
    const _matcherRoute = getMatcherRoutes()
    store.commit('setRoutes', _matcherRoute.children.map(c => c.meta && c.meta.title) || [])

    const newRouter = new VueRouter({
        routes: [
            errorRoute,
            _matcherRoute
        ]
    })

    router.matcher = newRouter.matcher
}

export const sidebarRoutes = () => {
    return getSidebarRoutes().children || []
}

const router = new VueRouter({
    base: (publicPath && publicPath[process.env.NODE_ENV]) || '',
    routes: [
        errorRoute,
        distributeRoute
    ]
})

guard(router)

export default router